package com.jtjrenren.android.taxi.passenger.core.pay.main;

import android.text.TextUtils;

import com.anbang.pay.sdk.BangfubaoHelper;
import com.jtjrenren.android.taxi.passenger.Constants;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiBestCoupn;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiBfb;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiCommonT;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiCouList;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiOrderDetails;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiPayMsg;
import com.jtjrenren.android.taxi.passenger.bean.event.AliPayEvent;
import com.jtjrenren.android.taxi.passenger.bean.event.PayEvent;
import com.jtjrenren.android.taxi.passenger.manger.AppManger;
import com.jtjrenren.android.taxi.passenger.manger.api.ApiWorks;
import com.jtjrenren.android.taxi.passenger.manger.pay.ali.AliPayManger;
import com.jtjrenren.android.taxi.passenger.manger.pay.ali.PayResult;
import com.jtjrenren.android.taxi.passenger.manger.pay.weixin.WxPayManger;
import com.jtjrenren.android.taxi.passenger.utils.ModuleUtils;

import com.library.mvp.presenter.BasePresenter;
import com.library.utils.LogUtil;
import com.library.utils.StringUtils;
import com.tencent.mm.sdk.modelbase.BaseResp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by wdl on 2016/9/21.
 */
public class PayPresenterImpl extends BasePresenter<PayView, PayInteractor> implements PayPresenter {
    public static final int PAYTYPE_QB = 0;
    public static final int PAYTYPE_WEIXIN = 2;
    public static final int PAYTYPE_ALI = 1;
    public static final int PAYTYPE_CRASH = 3;
    public static final int PAYTYPE_BFB = 4;

    private int currentPayType; //当前支付方式
    private ApiOrderDetails.MsgEntity orderDeatails; //订单详情
    private ApiCouList.DataListBean bestCoupons;  //最优打车劵

    public PayPresenterImpl(PayView view) {
        super(view);
    }

    @Override
    public void init() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData(String orderID) {
        if (orderID == null) {
            view.showTip("数据初始化错误，请稍后重试..");
            return;
        }

        view.refreshUserMoney(AppManger.getInstance().user.getRMBMoney());

        initPay(orderID);

        LogUtil.log("pay_main", "支付信息：" + orderID);
    }

    @Override
    public void destory() {
        EventBus.getDefault().unregister(this);
    }


    /**
     * 通过订单id 获取订单详情 然后加载界面
     *
     * @param orderID
     */
    private void initPay(String orderID) {
        view.showWaitting("数据加载中.....");
        interactor.getOrderDetails(orderID, new ApiWorks.ResponseListener<ApiOrderDetails>() {
            @Override
            public void onResponse(ApiOrderDetails apiOrderDetails) {
                view.dissWaitting();
                if (apiOrderDetails != null && apiOrderDetails.getMsg() != null) {
                    LogUtil.log("order", "获取订单详情结果:" + apiOrderDetails.getMsg().toString());
                    orderDeatails = apiOrderDetails.getMsg();

                    double payPrice = Double.parseDouble(StringUtils.isEmpty(orderDeatails.getAmount()) ? "0" : orderDeatails.getAmount());
                    double tip = Double.parseDouble(StringUtils.isEmpty(orderDeatails.getTipsTotal()) ? "0" : orderDeatails.getTipsTotal());
                    if (getOrderType() == Constants.CARTYPE_TAXI) {
                        view.showPayTaxiView();
                        view.refreshTipMoney(orderDeatails.getTipsTotal() + "");

                        if (payPrice == 0 || payPrice == tip)
                            view.refreshOrderMoney("");
                        else if (payPrice > 0)
                            view.refreshOrderMoney((payPrice - tip) + "");
                    } else {
                        view.showPaySpecarView();
                        view.refreshOrderMoney(payPrice + "");
                    }
                    view.refreshSjZfMoney(payPrice + "");
                    getBestCoupons(payPrice);

                } else {
                    view.showTip("数据加载异常，请稍候重试....");
                }
            }
        });

    }

    /**
     * 获取最优打车劵
     *
     * @param payPrice
     */
    private void getBestCoupons(double payPrice) {
        interactor.getBestCoupons(AppManger.getInstance().user.getWorkNo(), payPrice + "", getOrderType(), new ApiWorks.ResponseListener<ApiBestCoupn>() {
            @Override
            public void onResponse(ApiBestCoupn apiBestCoupn) {
                if (apiBestCoupn != null && apiBestCoupn.getDataList() != null && apiBestCoupn.getDataList().size() > 0) {
                    ApiCouList.DataListBean coupons = new ApiCouList.DataListBean();
                    coupons.setID(apiBestCoupn.getDataList().get(0).getID());
                    coupons.setDenomination(apiBestCoupn.getDataList().get(0).getDenomination() + "");
                    refreshCoupons(coupons);
                }
            }
        });
    }


    private interface PayResultListener<T> {
        void returnResult(T t);
    }

    private void doCrashPayN() {
        doHtPay("6", null);
    }

    private void doQBPay() {
        doHtPay("0", null);
    }

    private void doWeixinPay() {
        PayResultListener listener = new PayResultListener<ApiPayMsg>() {
            @Override
            public void returnResult(ApiPayMsg o) {
                WxPayManger wxPayManger = new WxPayManger();
                wxPayManger.initManger(view.getActivity());
                if (!wxPayManger.pay2(o.getPostData())) {
                    view.showTip("当前环境不支持微信支付");
                }
            }
        };


        doHtPay("2", listener);

    }

    private void doAliPay() {
        PayResultListener listener = new PayResultListener<ApiPayMsg>() {
            @Override
            public void returnResult(ApiPayMsg o) {
                AliPayManger manger = new AliPayManger();
                manger.pay2(view.getActivity(), o.getPostData());
            }
        };

        doHtPay("1", listener);
    }

    /**
     * 邦付宝支付
     */
    private void doBfbPay() {
        PayResultListener listener = new PayResultListener<ApiBfb>() {
            @Override
            public void returnResult(ApiBfb info) {
                LogUtil.log("pay", "帮付宝结果："+Thread.currentThread().toString()+"-----" + info.toString());
                BangfubaoHelper.getInstance().setTest(true);
                BangfubaoHelper.getInstance().payWithToken(view.getActivity(), BangfubaoHelper.PayType.PayTypeBFBAccountPay,
                        info.getOrderToken(), info.getTradeNo(), info.getMerchantSign(), "10");
            }
        };
        doHtPay("7", listener);
    }

    /**
     * 向后台发起支付
     *
     * @param payMode
     * @param listener
     */
    private void doHtPay(String payMode, final PayResultListener listener) {
        //money应该为不包含小费的金额
        String pay_money = view.getInputMoney();

        if (currentPayType != PAYTYPE_CRASH) {
            String money = StringUtils.isEmpty(pay_money) ? "0" : pay_money;
            if (Double.parseDouble(money) <= 0) {
                view.showTip("车费输入错误！");
                return;
            }
        }

        view.showWaitting("支付发起中，请稍候...");

        if (StringUtils.isEmpty(pay_money))
            pay_money = "0";
        if (getOrderType() == Constants.CARTYPE_SPECAR)
            pay_money = ModuleUtils.formatPoint(Double.parseDouble(orderDeatails.getAmount()) - Double.parseDouble(orderDeatails.getTipsTotal()), 1) + "";

        String couponsID = "";
        String couponsAmt = "";
        if (bestCoupons != null) {
            couponsID = bestCoupons.getID();
            couponsAmt = bestCoupons.getDenomination() + "";
        }

        interactor.payN(orderDeatails.getOrderID(), pay_money, payMode, couponsID, couponsAmt, new ApiWorks.ResponseListener<String>() {
            @Override
            public void onResponse(String result) {
                view.dissWaitting();
                if (currentPayType == PAYTYPE_BFB) {
                    ApiCommonT commonT = ModuleUtils.getCommonApi(result, ApiBfb.class);
                    if (commonT.getCode() == 1 && commonT.getData() != null && commonT.getData().size() > 0) {
                        if (listener != null)
                            listener.returnResult(commonT.getData().get(0));
                    } else {
                        payResult(false, commonT.getMsg());
                    }
                    return;
                }
                ApiCommonT commonApi = ModuleUtils.getCommonApi(result, ApiPayMsg.class);
                if (commonApi.getCode() == 1) {
                    if (commonApi.getData() != null && commonApi.getData().size() > 0) {
                        ApiPayMsg payMsg = (ApiPayMsg) commonApi.getData().get(0);
                        if (!StringUtils.isEmpty(payMsg.getPostData()))
                            listener.returnResult(payMsg);
                        else
                            payResult(true, commonApi.getMsg());
                    } else
                        payResult(true, "");
                } else
                    payResult(false, commonApi.getMsg());
            }
        });
    }


    /**
     * 支付结果
     *
     * @param isSuccess
     */
    private void payResult(boolean isSuccess, String desc) {

        if (!StringUtils.isEmpty(desc))
            view.showTip(desc);

        if (isSuccess) {
            if (currentPayType == PAYTYPE_QB)
                AppManger.getInstance().refreshQBYE(null);

            view.showResultPage(orderDeatails.getOrderID(), orderDeatails.getAmount(), true);
        }

    }

    @Override
    public void doPay() {

        if (currentPayType == PAYTYPE_CRASH)
            doCrashPayN();
        else if (currentPayType == PAYTYPE_ALI)
            doAliPay();
        else if (currentPayType == PAYTYPE_WEIXIN)
            doWeixinPay();
        else if (currentPayType == PAYTYPE_QB)
            doQBPay();
        else if (currentPayType == PAYTYPE_BFB)
            doBfbPay();

    }

    @Override
    public void payTypeChange(int type) {
        currentPayType = type;
    }


    @Override
    public void refreshCoupons(ApiCouList.DataListBean info) {
        this.bestCoupons = info;
        view.refreshBestCouponsView(info);
        refreshRealMoney(view.getInputMoney());
    }

    @Override
    public void refreshRealMoney(String money) {
        if (StringUtils.isEmpty(money) || ".".equals(money))
            money = "0";

        double m;
        if (getOrderType() == Constants.CARTYPE_TAXI)
            m = ModuleUtils.formatPoint((Double.parseDouble(money) + Double.parseDouble(orderDeatails.getTipsTotal())), 1);
        else
            m = ModuleUtils.formatPoint(Double.parseDouble(money), 1);
        if (bestCoupons != null)
            m = m - Double.parseDouble(bestCoupons.getDenomination());

        view.refreshSjZfMoney(ModuleUtils.formatPoint((m < 0 ? 0 : m), 1) + "");
    }

    @Override
    public int getOrderType() {
        if (orderDeatails == null)
            return -1;
        return Integer.parseInt(orderDeatails.getOrderType());
    }

    @Override
    public ApiCouList.DataListBean getBestCoupons() {
        return bestCoupons;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handAliPayEvent(AliPayEvent event) {
        PayResult aliResult = new PayResult(event.getResult());
        String payStatus = aliResult.getResultStatus();

        if (TextUtils.equals(payStatus, "9000"))
            payResult(true, "");
        else if (TextUtils.equals(payStatus, "8000"))
            view.showTip("支付结果确认中");
        else {
            payResult(false, "支付失败");
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handPayEvent(PayEvent event) {
        int mode = event.getPayMode();
        if (mode == PayEvent.MODE_THRIDPAY_START) {
            view.dissWaitting();
        }
    }

    //处理微信支付返回的结果
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handWxPayEvent(BaseResp event) {
        if (event.errCode == 0) {
            payResult(true, "");
        } else if (event.errCode == -1 || event.errCode == -2) {
            payResult(false, "支付失败");
        }
    }

    @Override
    public PayInteractor createInteractor() {
        return new PayInteractorImpl();
    }


}
